from datetime import datetime
from exts import db
import json

class UserModel(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    openid = db.Column(db.String(100), unique=True)  # 微信openid
    nickname = db.Column(db.String(100))  # 微信昵称，可选
    avatar_url = db.Column(db.String(255))
    gender = db.Column(db.Integer)
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    def get_stats(self):
        # 获取用户发帖数量
        post_count = Community_PostModel.query.filter_by(user_id=self.id).count()
        
        # 获取用户获赞数量（所有帖子的点赞总和）
        like_count = db.session.query(db.func.sum(Community_PostModel.like_count))\
            .filter_by(user_id=self.id).scalar() or 0
            
        return {
            'post_count': post_count,
            'like_count': int(like_count)
        }

class Community_PostModel(db.Model):
    __tablename__ = 'community_posts'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    images = db.Column(db.Text)  # 存储图片路径列表
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    create_time = db.Column(db.DateTime, default=datetime.now)
    like_count = db.Column(db.Integer, default=0)
    comment_count = db.Column(db.Integer, default=0)
    post_type = db.Column(db.String(20), nullable=False)  # partner, lost_found, community
    partner_type = db.Column(db.String(20))  # entertainment, sports, study, travel, others
    community_type = db.Column(db.String(50))  # 社区类型
    lost_found_type = db.Column(db.String(20))  # lost, found

class PostComment(db.Model):
    __tablename__ = 'post_comments'
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('community_posts.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    create_time = db.Column(db.DateTime, default=datetime.now)

class PostLike(db.Model):
    __tablename__ = 'post_likes'
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('community_posts.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    create_time = db.Column(db.DateTime, default=datetime.now)
